#coding=utf-8
from uliweb.orm import *
from uliweb.utils.common import get_var
from sqlalchemy.sql import not_

def get_modified_user():
    from uliweb import request
    
    return request.user.id

#任务书信息表
class Assignment(Model):  
    __verbose_name__ = u'任务书'
      
    ass_id = Field(CHAR, verbose_name='编号', max_length=20, required=True, unique=True, index=True)
    name = Field(str, max_length=255, verbose_name='任务书名称',required=True)
    kfzx = Reference('kfzx', verbose_name='开发中心', required=True)
    tx = ManyToMany('tx', verbose_name='条线', required=True, collection_name='tx_assignments')
    type = Field(CHAR, verbose_name='类型',max_length=1,required=True, choices=get_var('PARA/ASSIGNMENT_TYPE'))
    stage = Field(CHAR, verbose_name='所处阶段', max_length=20, required=True, choices=[])
    main_assignment_id = Field(CHAR, verbose_name='主任务书编号',max_length=20)
    release_date = Field(datetime.date, verbose_name='任务书下发时间', required=True)
    begin_date = Field(datetime.date, verbose_name='开始时间', required=True)
    end_date = Field(datetime.date, verbose_name='结束时间', required=True)
    status = Field(CHAR, max_length=10, verbose_name='执行情况', required=True, choices=get_var('PARA/ASSIGNMENT_STATUS'), default='1')
    delay_classes = Field(CHAR, max_length=2, verbose_name='延迟原因分类', choices=get_var('PARA/ASSIGNMENT_DELAY_CLASSES'))
    delay_reason = Field(TEXT, verbose_name='延迟原因说明')
    advanced_if = Field(bool, verbose_name='是否提前进场')
    risk_if = Field(bool, verbose_name='是否存在风险')
    risk_reason = Field(TEXT, verbose_name='风险说明')
    amount_inner = Field(float,verbose_name='中心工作量(人天)',required=True)
    amount_outer = Field(float,verbose_name='公司工作量(人天)',required=True)
    amount_inner_thisyear = Field(float,verbose_name='中心工作量-本年度(人天)',required=True)
    amount_outer_thisyear = Field(float,verbose_name='公司工作量-本年度(人天)',required=True)
    memo = Field(TEXT, verbose_name='备注')    
    modified_date = Field(datetime.datetime, verbose_name='修改时间', auto_now=True, auto_now_add=True)
    modified_user = Reference('user', verbose_name='修改人', collection_name='modifier_assignments', default=get_modified_user, auto=True, auto_add=True)
    requirements = ManyToMany('requirement', verbose_name='对应准开发需求', collection_name='req_assignments')
    systems = ManyToMany('system', verbose_name='对应系统', collection_name='sys_assignments', required=True)
    acceptance_finish_date = Field(datetime.date, verbose_name='验收完成日期')
    finish_date = Field(datetime.date, verbose_name='实际完成日期')
    
    class Table:
        fields = [
            {'name':'ass_id', 'width':120},
            {'name':'name', 'width':120},
            {'name':'kfzx', 'width':60},
            {'name':'type', 'width':80},
            {'name':'stage', 'width':60},
            {'name':'begin_date', 'width':80},
            {'name':'end_date', 'width':80},
            {'name':'acceptance_finish_date', 'width':80},
            {'name':'finish_date', 'width':80},
            {'name':'status', 'width':60},
            {'name':'systems', 'width':120},
            {'name':'tx'},
        ]
    
    class AddForm:
        fields = ('ass_id', 'name', 'kfzx', 'tx', 'type', 'stage', 'main_assignment_id',  
            'release_date', 'begin_date', 'end_date', 'amount_inner', 'amount_outer', 'memo',
            'requirements', 'systems')
        
    class EditForm:
        fields = ('ass_id', 'name', 'kfzx', 'tx', 'type', 'stage', 'main_assignment_id',  
            'release_date', 'begin_date', 'end_date', 'acceptance_finish_date',
            'finish_date', 'status', 'delay_classes', 
            'delay_reason', 'advanced_if', 'risk_if', 'risk_reason', 'amount_inner', 
            'amount_outer', 'amount_inner_thisyear', 'amount_outer_thisyear', 'memo', 
            'requirements', 'systems')
    
    class DetailView:
        fields = ('ass_id', 'name', 'kfzx', 'tx', 'type', 'stage', 'main_assignment_id',  
            'release_date', 'begin_date', 'end_date', 'acceptance_finish_date',
            'finish_date', 'status', 'delay_classes',
            'delay_reason', 'advanced_if', 'risk_if', 'risk_reason', 'amount_inner', 
            'amount_outer', 'amount_inner_thisyear', 'amount_outer_thisyear', 'memo', 
            'requirements', 'systems')
    
    def __unicode__(self):
        return u'%s-%s' % (self.ass_id, self.name)
    
    def get_url(self):
        return u'<a href="/assignments/%d" title="%s">%s</a>' % (self.id, unicode(self), unicode(self))
    
    class Meta:
        display_field = 'name'
        order_by = 'ass_id'
        
    def can_modify(self, user):
        if user.department == '2':
            if user.is_gm:
                return self._kfzx_ == user._kfzx_
            else:
                return set(self.systems.ids()) & set(user.users_systems.ids())
        elif user.department == '1':
            return self.tx.has(user._tx_)
    
    @classmethod
#    def get_user_assignments(cls, user, not_in=('FN',)):
    def get_user_assignments(cls, user, not_in=()):
        condition = None
        if user.department == '2' and not user.is_gm:
            ids = user.users_systems.ids()
            condition = cls.systems.in_(*ids) & condition
            
        if user.department == '1' and not user.is_gm:
            condition = cls.tx.in_(user._tx_) & condition
        
        if not_in:
            condition = not_(cls.c.stage.in_(not_in)) & condition
            
        return cls.filter(condition)
    
    def get_receiver_ids(self, sender_id):
        users = set([self.modified_user.id])
        User = get_model('user')
        test_user = User.filter(User.c.department =='3')
        
        for x in self.systems.all():
            users.update(set(x.users.ids()))
        if sender_id in users:
            users.remove(sender_id)
        for row in test_user:
            if row.id in users:
                users.remove(row.id)
            
        return list(users)
    